import React, { useEffect, useState } from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  RefreshControl
} from 'react-native';
import { LinearGradient } from 'expo-linear-gradient';
import { BlurView } from 'expo-blur';
import { Ionicons } from '@expo/vector-icons';
import { useAuth } from '../contexts/AuthContext';
import { userAPI } from '../utils/api';
import { theme } from '../styles/theme';

const HomeScreen = ({ navigation }) => {
  const { user, logout } = useAuth();
  const [balance, setBalance] = useState(null);
  const [refreshing, setRefreshing] = useState(false);

  useEffect(() => {
    fetchBalance();
  }, []);

  const fetchBalance = async () => {
    try {
      const response = await userAPI.getBalance(user.id);
      if (response.success) {
        setBalance(response.data.balance);
      }
    } catch (error) {
      console.error('Fetch balance error:', error);
    }
  };

  const onRefresh = async () => {
    setRefreshing(true);
    await fetchBalance();
    setRefreshing(false);
  };

  const menuItems = [
    { id: 1, title: '余额查询', icon: 'wallet-outline', screen: 'Balance', color: '#FFD700' },
    { id: 2, title: '消费记录', icon: 'receipt-outline', screen: 'Transactions', color: '#FFA500' },
    { id: 3, title: '寄存酒', icon: 'wine-outline', screen: 'Wines', color: '#FF6B6B' },
    { id: 4, title: '个人中心', icon: 'person-outline', screen: 'Profile', color: '#4ECDC4' }
  ];

  return (
    <LinearGradient colors={['#000000', '#1a1a1a']} style={styles.container}>
      <ScrollView
        contentContainerStyle={styles.scrollContent}
        refreshControl={
          <RefreshControl refreshing={refreshing} onRefresh={onRefresh} tintColor={theme.colors.primary} />
        }
      >
        {/* 头部 */}
        <View style={styles.header}>
          <View>
            <Text style={styles.greeting}>你好,</Text>
            <Text style={styles.username}>{user?.name}</Text>
          </View>
          <TouchableOpacity onPress={logout}>
            <Ionicons name="log-out-outline" size={28} color={theme.colors.primary} />
          </TouchableOpacity>
        </View>

        {/* 余额卡片 */}
        <BlurView intensity={30} tint="dark" style={styles.balanceCard}>
          <LinearGradient
            colors={['rgba(212, 175, 55, 0.1)', 'rgba(255, 215, 0, 0.05)']}
            style={styles.balanceGradient}
          >
            <Text style={styles.balanceLabel}>当前余额</Text>
            <Text style={styles.balanceAmount}>
              ¥{balance !== null ? parseFloat(balance).toFixed(2) : '---'}
            </Text>
            <View style={styles.balanceDecor} />
          </LinearGradient>
        </BlurView>

        {/* 菜单网格 */}
        <View style={styles.menuGrid}>
          {menuItems.map((item) => (
            <TouchableOpacity
              key={item.id}
              onPress={() => navigation.navigate(item.screen)}
              activeOpacity={0.8}
            >
              <BlurView intensity={20} tint="dark" style={styles.menuItem}>
                <View style={[styles.menuIconContainer, { backgroundColor: item.color + '20' }]}>
                  <Ionicons name={item.icon} size={32} color={item.color} />
                </View>
                <Text style={styles.menuTitle}>{item.title}</Text>
              </BlurView>
            </TouchableOpacity>
          ))}
        </View>
      </ScrollView>
    </LinearGradient>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1
  },
  scrollContent: {
    padding: theme.spacing.lg,
    paddingTop: theme.spacing.xxl
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: theme.spacing.xl
  },
  greeting: {
    fontSize: theme.fontSizes.large,
    color: theme.colors.textSecondary
  },
  username: {
    fontSize: theme.fontSizes.xxlarge,
    fontWeight: 'bold',
    color: theme.colors.text,
    marginTop: theme.spacing.xs
  },
  balanceCard: {
    borderRadius: theme.borderRadius.large,
    overflow: 'hidden',
    marginBottom: theme.spacing.xl,
    borderWidth: 1,
    borderColor: theme.colors.border
  },
  balanceGradient: {
    padding: theme.spacing.xl,
    minHeight: 160
  },
  balanceLabel: {
    fontSize: theme.fontSizes.medium,
    color: theme.colors.textSecondary,
    marginBottom: theme.spacing.sm
  },
  balanceAmount: {
    fontSize: theme.fontSizes.massive,
    fontWeight: 'bold',
    color: theme.colors.primary,
    letterSpacing: 2
  },
  balanceDecor: {
    position: 'absolute',
    right: -20,
    bottom: -20,
    width: 100,
    height: 100,
    borderRadius: 50,
    backgroundColor: theme.colors.primary,
    opacity: 0.05
  },
  menuGrid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'space-between'
  },
  menuItem: {
    width: (theme.spacing.xl * 4.5),
    padding: theme.spacing.lg,
    borderRadius: theme.borderRadius.medium,
    marginBottom: theme.spacing.md,
    alignItems: 'center',
    borderWidth: 1,
    borderColor: theme.colors.border
  },
  menuIconContainer: {
    width: 64,
    height: 64,
    borderRadius: theme.borderRadius.medium,
    alignItems: 'center',
    justifyContent: 'center',
    marginBottom: theme.spacing.md
  },
  menuTitle: {
    fontSize: theme.fontSizes.medium,
    color: theme.colors.text,
    textAlign: 'center'
  }
});

export default HomeScreen;
